//
//  OAuthViewController.swift
//  SinaWeibo
//
//  Created by 臧英振 on 16/2/7.
//  Copyright © 2016年 zyz. All rights reserved.
//

import UIKit
import SVProgressHUD

class OAuthViewController: UIViewController {

    //属性的webView
    let webView = UIWebView()
    
    //关闭页面
    @objc private func close() {
        
        //disimiss页面
        dismissViewControllerAnimated(true, completion: nil)
        
    }
    
    override func loadView() {
        //将根视图 替换为 webView
        view = webView
        //设置代理
        webView.delegate = self 
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        
        //文字渲染颜色
        //只正对当前的导航视图控制器有效
        
        setNavBar()
        
        //加载授权页面
        loadOAuthPage()
    }
    
    private func setNavBar() {
        
        self.navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", style: .Plain, target: self, action: "close")
    }


    //加载授权页面
    private func loadOAuthPage() {
        
        //获取url
        let urlString = "https://api.weibo.com/oauth2/authorize?" + "client_id=" + "1957664129" + "&redirect_uri=" + "http://www.itcast.cn"
        //可选的url
        let url = NSURL(string: urlString)!
        //获取request
        let request = NSURLRequest(URL: url)
        
        webView.loadRequest(request)
    }
    
}

//swift中 这样写 是将一类的协议方法 写在一起 更好阅读和维护
//同一类的协议方法 就被放在一个扩展中
extension OAuthViewController: UIWebViewDelegate {
    
    //显示 用户等待指示器
    func webViewDidStartLoad(webView: UIWebView) {
        //显示
        SVProgressHUD.show()
    }
    
    func webViewDidFinishLoad(webView: UIWebView) {
        //隐藏
        SVProgressHUD.dismiss()
    }
    
    //非常重要的协议方法
    //通常协议方法 返回值为bool类型 返回 yes 通常控件可以正常运行
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        guard let urlString = request.URL?.absoluteString else {
            //无法获取url字符串 就直接不加载网页
            return false
        }
        
        if urlString.containsString("code=") {
            //将url中的参数获取到
            guard let query = request.URL?.query else {
                return false
            }
            let codeStr = "code="
            //将 query 转换NSString subString
            let code = (query as NSString).substringFromIndex(codeStr.characters.count)
            print(code,query)
            //不希望页面跳转到 回调页面
            return false
        }
        return true
    }
    
}

